<% content_for :top_menu do %>
  <%= render :partial => 'admin/houses/templates/top_menu' %>
  <%= link_to "Назад", admin_root_path %>
<% end %>

<% content_for :header do %>

  <%= javascript_include_tag 'prototype.js' %>

  <script type="text/javascript">
    function change_position(request) {
      object = request.responseText.evalJSON();
      if (object["result"] == null) {
        swap(object["item1"]["id"], object["item2"]["id"]);
      }
    };

    function swap(id1, id2) {
      var container1 = document.getElementById("item" + id1);
      var container2 = document.getElementById("item" + id2);
      var html = container1.innerHTML;
      container1.innerHTML = container2.innerHTML;
      container2.innerHTML = html;
      container1.id = "item" + id2;
      container2.id = "item" + id1;
    };

    var houses = new Array();

    function save_positions() {
      var values = new Array();
      for(var i = 0; i < houses.length; i++) {
        var value = $(houses[i][0]).getValue();
        values.push({'id': houses[i][1], 'value': value})
      }
      new Ajax.Request('/admin/houses/update_positions',
			  {evalScripts: true,
			   parameters: {values: values.toJSON(), page: <%= params[:page].to_i %>},
			   asynchronous: true,
			   onComplete: function(request) {
			   	 new Ajax.Updater('rent', '/admin/houses/update_container', {
              parameters: {page: <%= params[:page].to_i %>, house_type: 'rent'}
			   	 });
			   }
			  });
  		return false;
    };

function save_categories() {
  var values = [];
  for(var i = 0; i < houses.length; i++) {
    console.log(houses[i][1]);

    var value = $('house_category_id_' + houses[i][1]).getValue();
    values.push({'id': houses[i][1], 'value': value})
  }

  new Ajax.Request('/admin/houses/update_categories',
    {evalScripts: true,
      parameters: {values: values.toJSON(), page: <%= params[:page].to_i %>},
      asynchronous: true,
      onComplete: function(request) {
      new Ajax.Updater('rent', '/admin/houses/update_container', {
        parameters: {page: <%= params[:page].to_i %>, house_type: 'rent'}
      });
      }
    });
    return false;
}
    </script>
<% end %>

<div id="container">
  <h1>Дома для аренды</h1>
  <div id="rent">
    <%= render :partial => "editable_house", :collection => @houses_rent, :locals => {:house_type => "rent"} %>
  </div>
  <%= will_paginate @houses_rent %>
</div>

<p>
  <%= button_to_function "Сохранить Позиции", "save_positions();" %>
  <%= button_to_function "Сохранить Категории", "save_categories();" %>
</p>
